package com.bitcat.firstapp.demo.musicdemo

import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bitcat.firstapp.R
import com.bitcat.firstapp.databinding.ActivityMusicDetailBinding

class MusicDetailActivity : AppCompatActivity() {

    private var musicInfo: MusicInfo? = null

    private val binding: ActivityMusicDetailBinding by lazy {
        ActivityMusicDetailBinding.inflate(layoutInflater)
    }

    private val receiver = object :BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == "MUSIC_END"){
                //播放完成
                isPlaying = false
                updateButton()
                handler.removeCallbacks(runnable)
                binding.seekBar.progress = 0
                binding.tvCurrentTime.text = formatTime(0)
            }
        }
    }

    private val handler = Handler(Looper.getMainLooper())

    private val runnable = object :Runnable{
        override fun run() {
           //主要更新seekbar 和当前播放进度文字
            binding.seekBar.progress = musicService?.getCurrentPosition() ?: 0
            binding.tvCurrentTime.text = formatTime(musicService?.getCurrentPosition()?.toLong() ?: 0)

            //每隔1秒更新一次
            handler.postDelayed(this,1000)
        }
    }

    //是否在播放音乐
    private var isPlaying = false

    private var musicService: MusicService? = null

    private val conn = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            musicService = (service as MusicService.MusicBinder).getMusicService()
            startPlayMusic()
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            musicService = null
        }
    }


    //  播放音乐
    private fun startPlayMusic() {
        musicInfo?.let {
            musicService?.playMusic(it.path)
            isPlaying = true
            binding.seekBar.max = musicService?.getDuration() ?: 0  //  设置进度条最大值
            updateButton()
            handler.post(runnable)
        }

    }



    // 播放暂停的按钮图标
    private fun updateButton() {
        binding.playPauseButton.setImageResource(if (isPlaying) android.R.drawable.ic_media_pause else android.R.drawable.ic_media_play)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(30, systemBars.top, 30, systemBars.bottom)
            insets
        }

        musicInfo = intent.getParcelableExtra("music")

        binding.tvTitle.text = musicInfo?.title
        binding.tvArtist.text = musicInfo?.artist
        binding.tvTotalTime.text = formatTime(musicInfo?.duration ?: 0)

        bindMusicService()
        setListeners()
    }

    private fun setListeners() {

        registerReceiver(receiver, IntentFilter("MUSIC_END"))

        //播放暂停
        binding.playPauseButton.setOnClickListener {
            if (isPlaying){
                pauseMusic()
            }else{
                resumeMusic()
            }
        }

        //seekbar的拖动监听
        binding.seekBar.setOnSeekBarChangeListener(object :OnSeekBarChangeListener{

            //进度条进度改变
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser){
                    binding.tvCurrentTime.text = formatTime(progress.toLong())
                }
            }

            //开始拖动
            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                handler.removeCallbacks(runnable) //暂停停掉每隔一秒钟更新
            }

            //停止拖动
            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                val progress = seekBar?.progress ?: 0
                musicService?.seekTo(progress)
                if (isPlaying){
                    handler.post(runnable)
                }
            }
        })
    }

    // 继续播放
    private fun resumeMusic() {
        musicService?.resumeMusic()
        isPlaying = true
        updateButton() // 更新按钮
        handler.post(runnable)
    }

    //暂停播放
    private fun pauseMusic() {
        musicService?.pauseMusic()
        isPlaying = false
        updateButton() // 更新按钮
        handler.removeCallbacks(runnable) // 移除进度更新回调
    }

    private fun bindMusicService() {
        val intent = Intent(this, MusicService::class.java)
        bindService(intent, conn, BIND_AUTO_CREATE)
        startService(intent)
    }


    private fun formatTime(duration: Long): String {
        val minutes = duration / 1000 / 60
        val seconds = duration / 1000 % 60
        return String.format("%02d:%02d", minutes, seconds)
    }


    override fun onDestroy() {
        super.onDestroy()
        unbindService(conn)
    }
}